package com.atguigu.flink01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/2/18
 * 该案例演示了以批的形式对有界流数据进行处理
 */
public class Flink01_WC_Bound_Batch {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定批处理环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //TODO 2.从指定的文件中读取数据
        DataSource<String> dataSource = env.readTextFile("D:\\dev\\workspace\\bigdata-0918\\flink-0918\\input\\word.txt");
        //TODO 3.对读取的数据进行切分
        FlatMapOperator<String, Tuple2<String, Integer>> flatDS = dataSource.flatMap(
                new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String lineStr, Collector<Tuple2<String, Integer>> out) throws Exception {
                        //对读取的一行数据进行切分
                        String[] words = lineStr.split(" ");
                        //遍历出数组中的每一个元素
                        for (String word : words) {
                            //将遍历出来的元素封装为一个二元组 传递到下游
                            out.collect(Tuple2.of(word, 1));
                        }
                    }
                }
        );
        //TODO 4.按照单词进行分组
        UnsortedGrouping<Tuple2<String, Integer>> groupDS = flatDS.groupBy(0);
        //TODO 5.计算单词出现的次数(求和)
        AggregateOperator<Tuple2<String, Integer>> sumDS = groupDS.sum(1);
        //TODO 6.打印
        sumDS.print();
    }
}
